<template>
    <div class="decorateMainIndex">
        <div class="wrapper">
            <div class="container" v-if="controls">
                <pageTopComponent v-if="controls[0].id" :id="controls[0].id" :ename="controls[0].ename"></pageTopComponent>
                <div class="body" :style="{ backgroundColor: controls[0].main.pageBgColor }">
                    <draggable class="listDropChapter" v-model="controls" handle=".dropChapter" v-bind="chapterOptions" @end="onDragEndHandle" v-if="controls && controls.length > 0">
                        <transition-group tag="ul" class="list">
                            <li class="item" v-for="(c, controlsIndex) in controls" :key="c.id" @click.stop="chooseThisControl(controlsIndex)" :class="c.active + ((c.ename == 'floatButtonComponent' || c.ename == 'backTopComponent') ? ' suspend' : c.fixedBottom ? '' : ' dropChapter')" :style="(
                  (c.ename == 'floatButtonComponent')?
                  ('width:'+ c.main.floatButtonSize + 'px;height:'+c.main.floatButtonSize + 'px;'
                  + 'left:'+((c.main.floatingButtonPositon == 'br' || c.main.floatingButtonPositon == 'tr') ? 'auto;' : c.main.leftAndRightOffset+'%;')
                  + 'top:'+((c.main.floatingButtonPositon == 'bl' || c.main.floatingButtonPositon == 'br') ? 'auto;' : (c.main.offsetUpAndDown +'%;'))
                  + 'right:'+((c.main.floatingButtonPositon == 'bl' || c.main.floatingButtonPositon == 'tl') ? 'auto;' : c.main.leftAndRightOffset + '%;')
                  + 'bottom:'+((c.main.floatingButtonPositon == 'tl' || c.main.floatingButtonPositon == 'tr') ? 'auto;' : c.main.offsetUpAndDown + '%;')
                  + 'zIndex:'+controlsIndex) :
                  
                  (c.ename == 'backTopComponent')?
                  ('width:'+((c.main.backTopSize + 10) + 'px;')
                  +('left:'+(c.main.buttonPosition == 'br' ? 'auto;'  : (c.main.leftAndRightOffset + '%;')))
                  +('right:'+(c.main.buttonPosition == 'bl' ? 'auto;' : (c.main.leftAndRightOffset + '%;')))
                  +('bottom:'+(c.main.offsetUpAndDown + '%;'))
                  +('zIndex:'+controlsIndex)) :
                  (c.ename == 'pageTopComponent')?'display:none;':
                  '')">

                                <div 
                                class="controlWrapper" 
                                v-if="controlsIndex > 0"
                                :style="(c.ename === 'backTopComponent') ? ('width:'+(c.main.backTopSize+10)+'px;') : ''"
                                >
                                    <component v-bind:is="c.ename" :controlsIndex="controlsIndex" :ename="c.ename" :item="c" :id="c.id"></component>
                                </div>

                                <el-popconfirm confirmButtonText="确认" cancelButtonText="取消" icon="el-icon-info" iconColor="red" title="确认删除该组件吗？" @confirm="delControl(controlsIndex)" v-if="controlsIndex > 0">
                                    <span class="delBtn" slot="reference" v-if="controlsIndex > 0 && c.ename != 'floatingButton' && c.ename != 'backToTop' && c.canDelete">删除</span>
                                </el-popconfirm>
                                
                            </li>
                        </transition-group>
                    </draggable>

                    <p class="empty" v-if="controls.length < 2">您还没有添加任何元素</p>



                    <dataPageFloatButton1 ref="dataPageFloatButton1" v-if="isShowDataPageFloatBtn"></dataPageFloatButton1>
                    <dataPageFloatButton2 ref="dataPageFloatButton2" v-if="isShowDataPageFloatBtn"></dataPageFloatButton2>





                </div>
                <div class="foot" v-if="controls[0].main.bottomMenu != 1 && bottomButtonData">
                    <FootComponent ref="footComponent" :bottomButtonData="bottomButtonData"></FootComponent>
                </div>
            </div>
        </div>


        <el-drawer
        title="页面预览"
        size="40%"
        append-to-body
        destroy-on-close
        :close-on-press-escape="false"
        :wrapperClosable="false"
        :visible.sync="isShowPreview"
        :before-close="beforeCloseElDrawer">
        <PagePreview ref="pagePreview"></PagePreview>
        </el-drawer>



    </div>
</template>

<script>
import Bus from "@/utils/bus";
import draggable from "vuedraggable";
import { mapState } from "vuex";
export default {
    name: "decorateMainIndex",
    data() {
        return {
            controls: null, //组件列表
            needUpdatePageTop: false, //是否需要更新顶部组件
            chapterOptions: {
                group: { name: "layout", pull: false, put: false },
                draggable: ".item.dropChapter",
                forceFallback: true,
                sort: true,
                animation: 300,
            },
            //是否显示预览
            isShowPreview: false, 
            //存放当前显示的底部菜单的配置数据
            bottomButtonData: null,
            //是否显示数据页悬浮按钮
            isShowDataPageFloatBtn: true,
        };
    },
    props: [],
    components: {
        draggable,
        pageTopComponent: () => import("./components/pageTopComponent.vue"),
        carouselImageComponent: () =>
            import("./components/carouselImageComponent.vue"),
        announcementComponent: () =>
            import("./components/announcementComponent.vue"),
        imageListComponent: () => import("./components/imageListComponent.vue"),
        buttonGroupComponent: () =>
            import("./components/buttonGroupComponent.vue"),
        listNavigationComponent: () =>
            import("./components/listNavigationComponent.vue"),
        titleComponent: () => import("./components/titleComponent.vue"),
        auxiliaryBlankComponent: () =>
            import("./components/auxiliaryBlankComponent.vue"),
        auxiliaryLineComponent: () =>
            import("./components/auxiliaryLineComponent.vue"),
        richTextComponent: () => import("./components/richTextComponent.vue"),
        floatButtonComponent: () =>
            import("./components/floatButtonComponent.vue"),
        backTopComponent: () => import("./components/backTopComponent.vue"),
        projectComponent: () => import("./components/projectComponent.vue"),
        memberComponent: () => import("./components/memberComponent.vue"),
        FootComponent: () => import("./components/footComponent.vue"),
        commissionTemplateHeadComponent: () => import("./components/commissionTemplateHeadComponent.vue"),
        commissionTemplateListComponent: () => import("./components/commissionTemplateListComponent.vue"),
        dataDetailsComponent: () => import("./components/dataDetailsComponent.vue"),
        myTeamHeadComponent: () => import("./components/myTeamHeadComponent.vue"),
        myTeamListComponent: () => import("./components/myTeamListComponent.vue"),
        codeManageHeadComponent: () => import("./components/codeManageHeadComponent.vue"),
        codeManageListComponent: () => import("./components/codeManageListComponent.vue"),
        billPageHeadComponent: () => import("./components/billPageHeadComponent.vue"),
        billPageListComponent: () => import("./components/billPageListComponent.vue"),
        invitationPageComponent: () => import("./components/invitationPageComponent.vue"),
        dataPageHeadComponent: () => import("./components/dataPageHeadComponent.vue"),
        dataPageListComponent: () => import("./components/dataPageListComponent.vue"),
        dataPageFloatButton1: () => import("./components/dataPageFloatButton1.vue"),
        dataPageFloatButton2: () => import("./components/dataPageFloatButton2.vue"),
        promoteBusinessListComponent: () => import("./components/promoteBusinessListComponent.vue"),
        promoteBusinessBottomComponent: () => import("./components/promoteBusinessBottomComponent.vue"),
        PagePreview: () => import("../preview/Index.vue"),
    },
    activated() {},
    created() {},
    mounted() {
        this.$nextTick(() => {
            this.init();
        });
        Bus.$off("showPreview");
        Bus.$on("showPreview",()=>{
            this.isShowPreview=true; 
            setTimeout(()=>{
                this.$refs.pagePreview.init();  
            },100)
        })
        Bus.$off("updateMain");
        Bus.$on("updateMain", (data) => {
            //console.log("main组件被通知更新");
            this.$nextTick(() => {
                if (data) {
                    //若需要更新顶部组件（相关信息）
                    if(data.update === "updatePageTop") {
                        this.controls = JSON.parse(JSON.stringify(this.decorate.controls));
                        //console.log("在main组件中，被要求通知PageTop更新");
                        const emitName =  this.controls[0].ename +  this.controls[0].id;
                        Bus.$emit(emitName, JSON.stringify(this.controls[0]));
                    }
                    //动了返回顶部组件，此处需要在外层更新
                    if(data.ename === "backTopSize"||data.ename === "buttonPosition"||data.ename === "offsetUpAndDown"||data.ename === "leftAndRightOffset") { 
                        this.controls[data.controlsIndex].main[data.ename] = data.value;
                    }
                    //动了悬浮组件，此处需要在外层更新
                    if(data.ename === "floatingButtonPositon"||data.ename === "offsetUpAndDown"||data.ename === "leftAndRightOffset") { 
                        this.controls[data.controlsIndex].main[data.ename] = data.value;
                    }
                    if(data.update === "dataPageFloatBtn1") {
                        this.$refs.dataPageFloatButton1.oItem = null;
                        this.$refs.dataPageFloatButton1.$nextTick(()=>{
                            this.$refs.dataPageFloatButton1.oItem = JSON.parse(data.control);
                        })
                    }
                    if(data.update === "dataPageFloatBtn2") {
                        this.$refs.dataPageFloatButton2.oItem = null;
                        this.$refs.dataPageFloatButton2.$nextTick(()=>{
                            this.$refs.dataPageFloatButton2.oItem = JSON.parse(data.control);
                        })
                    }
                }else{
                    this.controls = null;
                    this.controls = JSON.parse(JSON.stringify(this.decorate.controls));
                }
            });
        });
        //设置顶部组件时，通知及时更新是否显示页面底部按钮
        Bus.$off("updateMain_bottomMenu");
        Bus.$on("updateMain_bottomMenu", data => {
            this.controls[0].main.bottomMenu = data;
            this.$nextTick(()=>{
                if(data>1) {
                    //若需要显示底部菜单，则渲染其配置好的样式
                    //1、先从本地缓存中获取底部菜单列表
                    if(localStorage.getItem("bottomButtonList")) {
                        let bottomButtonList = JSON.parse(localStorage.getItem("bottomButtonList"));
                        //2、若本地缓存中存在底部菜单列表
                        if(bottomButtonList && bottomButtonList.length>0) {
                            let bottomButtonIndex = null;
                            //3、遍历底部菜单列表
                            for(let i=0; i<bottomButtonList.length; i++) {
                                //4、通过ID找出当前选中的底部菜单
                                if(bottomButtonList[i].id === data) {
                                    bottomButtonIndex = i;
                                    break;
                                }
                            }
                            
                                if(bottomButtonIndex!==null && parseInt(bottomButtonIndex)>=0) { 
                                    //5、将整个组件的配置数据全部赋到页面中的对象集合上
                                    if(bottomButtonList[bottomButtonIndex] && bottomButtonList[bottomButtonIndex].pageContent) {
                                        // setTimeout(()=>{ console.log("bottomButtonIndex",bottomButtonIndex);
                                        this.bottomButtonData = bottomButtonList[bottomButtonIndex].pageContent;
                                        // this.$refs.footComponent.pageContent = bottomButtonList[bottomButtonIndex].pageContent;
                                        // }, 200)
                                    }
                                }
                            
                        }
                    }
                }
            })
        })
        //设置顶部组件时，通知及时更新显示的页面背景颜色
        Bus.$off("updateMain_pageBgColor");
        Bus.$on("updateMain_pageBgColor", data => {
            this.controls[0].main.pageBgColor = data;
        })
    },
    methods: {
        //页面初始化
        init() {
            console.log("main init");
            let controls = null;
            controls = JSON.parse(JSON.stringify(this.decorate.controls));
            this.controls = controls;
            // console.log(controls);
            if(localStorage.getItem("bottomButtonList")) {
                let bottomButtonList = JSON.parse(localStorage.getItem("bottomButtonList"));
                bottomButtonList.forEach(item=>{
                    if(item.id == controls[0].main.bottomMenu) {
                        this.bottomButtonData = item.pageContent;
                    }
                })
            }
        },
        //点击 选中 当前组件，同时当前组件数据同步到右侧配置页
        chooseThisControl(index) {
            let controls = this.decorate.controls;
            //console.log("当前组件索引",index, "组件名称：",controls[index].ename,"当前激活状态：",controls[index].active,"===");
            //console.log("在Main中点选了组件：",controls[index].name);
            //若当前点击的组件正在激活状态
            if (controls[index] && controls[index].active == "active") {
                //则默认不做任何处理
                return false;
            }

            //若当前顶部组件正在激活状态
            if (controls[0].active == "active") {
                //则此次事件末尾，需要通知顶部组件更新
                this.needUpdatePageTop = true;
                //取消激活状态
                controls[0].active = "";
            } else {
                //否则不需要通知顶部组件更新
                this.needUpdatePageTop = false;
            }
            
            controls.forEach((row) => {
                row.active = "";
            });

            //console.log("在main中点选组件后通知更新")
            this.updateControls(index, controls);
        },
        //点击从主区域删除当前组件
        delControl(controlsIndex) {
            //console.log("在Main中删除组件：",this.decorate.controls[controlsIndex].name);
            let controls = this.controls;
            
            //从组件列表中移除
            controls = controls.filter((row, index) => index != controlsIndex);
            //获取列表中最后一个（新的）组件索引号
            let index = controls.length - 1;
            if (index == 0) {
                //若是顶部组件，则最后要通知顶部组件更新
                this.needUpdatePageTop = true;
            } else {
                //否则不用通知顶部组件更新
                this.needUpdatePageTop = false;
            }
            //通知更新
            this.updateControls(index, controls);
        },
        //更新组件数据
        updateControls(index, controls) {
            // //console.log(
            //     "更新：",
            //     index,
            //     "==",
            //     controls[index].ename,
            //     "==",
            //     controls[index].id
            // );
            //给当前最新组件设置激活状态
            controls[index].active = "active";
            //存入集合中
            this.$store.dispatch("controls", JSON.parse(JSON.stringify(controls)));
            //当前页更新
            this.init();
            //通知右侧更新
            // //console.log("通知右侧更新");
            Bus.$emit("updateRight", {index: index});
          
            if (this.needUpdatePageTop) {
                //通知顶部组件更新
                // //console.log("通知顶部组件更新");
                const emitName = controls[0].ename + controls[0].id;
                Bus.$emit(emitName, JSON.stringify(controls[0]));
            }
        },
        //拖拽排序结束的事件
        onDragEndHandle() {
            let controls = JSON.parse(JSON.stringify(this.controls));
            this.$store.dispatch("controls", JSON.parse(JSON.stringify(controls)));
            this.$nextTick(() => {
                this.init();
                let currentIndex = 0;
                controls.forEach((item, index) => {
                    if (item.active == "active") {
                        currentIndex = index;
                    }
                });
                //console.log("onDragEndHandle 通知右侧更新");
                Bus.$emit(`updateRight`, { index: currentIndex });
            });
        },
        //关闭预览弹窗
        beforeCloseElDrawer(){this.isShowPreview=false;}
    },
    computed: mapState(["decorate"]),
    watch: {},
    beforeDestroy() {
        if(this.decorate.controls && this.decorate.controls.length>0) {
            let controls = null;
            controls = this.decorate.controls.filter(c=>c.ename==="pageTopComponent");
            this.$store.dispatch("controls", JSON.parse(JSON.stringify(controls)));
            this.controls = controls
        }
    },
};
</script>

<style scoped lang="scss">
.decorateMainIndex {
    background-color: #f4f6f8;
    display: flex;
    flex: 1;
    justify-content: center;
    .wrapper {
        height: 100%;
        min-width: 496px;
        overflow-y: auto;
        position: relative;
        box-sizing: border-box;
        &::-webkit-scrollbar {
            display: none;
        }
        .container {
            width: 375px;
            box-shadow: 0px 4px 14px rgba(133, 148, 162, 0.2);
            margin: 50px auto;

            .body {
                background-color: #f5f5f5;
                width: 100%;
                display: flex;
                min-height: 617px;
                position: relative;
                flex-direction: column;
                .listDropChapter {
                    & > .list {
                        & > .item {
                            position: relative;
                          
                            .delBtn {
                                position: absolute;
                                top: -1px;
                                right: -31px;
                                z-index: 2;
                                width: 30px;
                                height: 14px;
                                background-color: red;
                                font-size: 12px;
                                color: #fff;
                                display: none;
                                justify-content: center;
                                align-items: center;
                                cursor: pointer;
                            }
                            &.active {
                                outline: #0079fe solid 1px;margin-bottom: 1px;
                                &:hover {
                                    outline: #0079fe solid 1px;margin-bottom: 1px;
                                }
                                .delBtn {
                                    display: flex;
                                }
                            }
                            &:hover {
                                outline: #0079fe solid 1px;margin-bottom: 1px;

                                .delBtn {
                                    display: flex;
                                }
                            }
                            &.suspend {
                                position: absolute;
                            }
                        }
                    }
                }
                .empty {
                    height: 100%;
                    width: 100%;
                    min-height: 300px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    font-size: 14px;
                }
            }
            .foot {
                width: 100%;
                height: 50px;
                background-color: #fff;
                border-top: 1px solid #eee;
                box-sizing: border-box;
                display: flex;
            }
        }
    }
}
</style>
